package com.example.campus.service.impl;


import com.example.campus.exception.*;
import com.example.campus.mapper.*;
import com.example.campus.pojo.dto.*;
import com.example.campus.pojo.entity.Admin;
import com.example.campus.pojo.vo.StatisticsVO;
import com.example.campus.result.PageResult;
import com.example.campus.service.AdminService;
import com.example.campus.utils.constant.MessageConstant;
import com.example.campus.utils.constant.PasswordConstant;
import com.example.campus.utils.constant.StatusConstant;
import com.example.campus.utils.context.BaseContext;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;


import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class AdminServiceImpl implements AdminService {

    @Autowired
    private AdminMapper adminMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LostAndFoundInfoMapper lostAndFoundInfoMapper;

    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private LikeMapper likeMapper;

    /**
     * 管理员注册
     * @param adminRegisterDTO
     */
    @Override
    public void register(AdminRegisterDTO adminRegisterDTO) {
        Admin admin = new Admin();
        //对象属性拷贝
        BeanUtils.copyProperties(adminRegisterDTO, admin);
        //设置密码
        admin.setPassword(DigestUtils.md5DigestAsHex(admin.getPassword().getBytes()));
        //设置账号状态，默认正常状态
        admin.setStatus(StatusConstant.ENABLE);
        //设置当前记录的创建时间和修改时间
        admin.setCreateTime(LocalDateTime.now());
        admin.setUpdateTime(LocalDateTime.now());

        adminMapper.insert(admin);
    }

    /**
     * 管理员登录
     *
     * @param adminLoginDTO
     * @return
     */
    @Override
    public Admin login(AdminLoginDTO adminLoginDTO) {
        String username = adminLoginDTO.getUsername();
        String password = adminLoginDTO.getPassword();

        //1、根据用户名查询数据库中的数据
        Admin admin = adminMapper.getByUsername(username);

        //2、处理各种异常情况（用户名不存在、密码不对、账号被锁定）
        if (admin == null) {
            //账号不存在
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }

        //密码比对
        password = DigestUtils.md5DigestAsHex(password.getBytes());
        if (!password.equals(admin.getPassword())) {
            //密码错误
            throw new PasswordErrorException(MessageConstant.PASSWORD_ERROR);
        }

        if (admin.getStatus() == StatusConstant.DISABLE) {
            //账号被锁定
            throw new AccountLockedException(MessageConstant.ACCOUNT_LOCKED);
        }

        //3、返回实体对象
        return admin;
    }

    /**
     * 新增管理员
     * @param adminAddDTO
     * @return
     */
    @Override
    public void add(AdminAddDTO adminAddDTO) {
        Admin admin = new Admin();

        //对象属性拷贝
        BeanUtils.copyProperties(adminAddDTO, admin);

        //设置账号状态，默认正常状态
        admin.setStatus(StatusConstant.ENABLE);

        //设置密码，默认密码为123456
        admin.setPassword(DigestUtils.md5DigestAsHex(PasswordConstant.DEFAULT_PASSWORD.getBytes()));

        //设置当前记录的创建时间和修改时间
        admin.setCreateTime(LocalDateTime.now());
        admin.setUpdateTime(LocalDateTime.now());


        adminMapper.insert(admin);
    }

    /**
     * 删除管理员
     * @param adminId
     */
    @Override
    public void delete(Long adminId) {
        //判断登录对象是否是boss，只有boss才能删除管理员
        Long currentId = BaseContext.getCurrentId();
        if (!adminMapper.getByAdminId(currentId).getUsername().equals(MessageConstant.BOSS)) {
            throw new NotBossException(MessageConstant.ONLY_BOSS);
        }

        Admin admin = adminMapper.getByAdminId(adminId);
        if (admin == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        adminMapper.deleteById(adminId);
    }

    /**
     * 管理员分页查询
     * @param adminPageQueryDTO
     * @return
     */
    @Override
    public PageResult pageQuery(AdminPageQueryDTO adminPageQueryDTO) {
        //判断登录对象是否是boss，只有boss才能查询管理员信息
        Long currentId = BaseContext.getCurrentId();
        if (!adminMapper.getByAdminId(currentId).getUsername().equals(MessageConstant.BOSS)) {
            throw new NotBossException(MessageConstant.ONLY_BOSS);
        }

        //开始分页查询
        PageHelper.startPage(adminPageQueryDTO.getPage(), adminPageQueryDTO.getPageSize());

        Page<Admin> page = adminMapper.pageQuery(adminPageQueryDTO);

        long total = page.getTotal();
        if (total < 1) {
            throw new QueryFailedException(MessageConstant.QUERY_NULL);
        }

        List<Admin> records = page.getResult();

        return new PageResult(total, records);
    }

    /**
     * 更新管理员信息
     * @param adminUpdateDTO
     */
    @Override
    public void update(AdminUpdateDTO adminUpdateDTO) {
        Long id = adminUpdateDTO.getId();
        Admin admin = adminMapper.getByAdminId(id);
        if (admin == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        adminMapper.update(adminUpdateDTO);
    }

    /**
     * 修改管理员状态
     * @param adminStatusChangeDTO
     */
    @Override
    public void changeAdminStatus(AdminStatusChangeDTO adminStatusChangeDTO) {
        //判断登录对象是否是boss，只有boss才能查询管理员信息
        Long currentId = BaseContext.getCurrentId();
        if (!adminMapper.getByAdminId(currentId).getUsername().equals(MessageConstant.BOSS)) {
            throw new NotBossException(MessageConstant.ONLY_BOSS);
        }

        Long adminId = adminStatusChangeDTO.getAdminId();
        Admin admin = adminMapper.getByAdminId(adminId);
        if (admin == null) {
            throw new AccountNotFoundException(MessageConstant.ACCOUNT_NOT_FOUND);
        }
        adminMapper.changeAdminStatus(adminStatusChangeDTO);
    }

    @Override
    public void updatePwd(PwdUpdateDTO pwdUpdateDTO) {
        Long id = BaseContext.getCurrentId();
        Admin admin = adminMapper.getByAdminId(id);
        if (!admin.getPassword().equals(DigestUtils.md5DigestAsHex(pwdUpdateDTO.getOldPwd().getBytes()))) {
            throw new PasswordNotMatchException(MessageConstant.OLD_PWD_ERROR);
        }
        if (!pwdUpdateDTO.getRePwd().equals(pwdUpdateDTO.getNewPwd())) {
            throw new PasswordNotMatchException(MessageConstant.RE_PWD_ERROR);
        }

        String newPwd = DigestUtils.md5DigestAsHex(pwdUpdateDTO.getNewPwd().getBytes());
        adminMapper.updatePwd(newPwd, id);
    }

    @Override
    public StatisticsVO getStatistics() {
        Map<String, Long> lostAndFoundInfoTotal = new HashMap<>();
        lostAndFoundInfoTotal.put("lost", lostAndFoundInfoMapper.getLostInfoTotal());
        lostAndFoundInfoTotal.put("found", lostAndFoundInfoMapper.getFoundInfoTotal());
        return StatisticsVO.builder()
                .userCount(userMapper.getUserTotal())
                .lostAndFoundInfoCount(lostAndFoundInfoTotal)
                .commentCount(commentMapper.getCommentTotal())
                .likeCount(likeMapper.getLikeTotal())
                .resolvedCount(lostAndFoundInfoMapper.getResolvedInfoTotal())
                .unresolvedCount(lostAndFoundInfoMapper.getUnresolvedInfoTotal())
                .build();
    }

}
